package com.tledu.spring06.spring04.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @author Antg
 * @date 2021/8/911:56
 */
@Component
@Aspect
public class UserAspect {
    /**
     * ..是任意的意思
     *
     * @param joinPoint
     */
    @Before("execution(public * com.tledu.spring04.dao..*.insert(..))")
    public void before(JoinPoint joinPoint) {
        System.out.println("注解方式----->拦截了");
        //这种方法仅适用一个类
//        User user = (User) joinPoint.getArgs()[0];
//        user.setCreateTime(new Date());
//        user.setCreateBy("张三");
        //利用反射
        Object[] args = joinPoint.getArgs();
        for (Object o : args) {
            Class c = o.getClass();
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if ("createBy".equals(field.getName())) {
                    try {
                        field.set(o, "张三");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                if ("createTime".equals(field.getName())) {
                    try {
                        field.set(o, new Date());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }
}
